package cn.jaye.fabric.domain.service;

import cn.jaye.fabric.common.constants.mapping.Table;
import cn.jaye.fabric.domain.model.MOrderer;
import cn.jaye.fabric.domain.model.Org;
import cn.jaye.fabric.domain.repository.OrdererRepository;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.hyperledger.fabric.sdk.HFClient;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.exception.InvalidArgumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jaye
 * @create 2018-05-15 11:18
 */
@Service
public class OrdererService {

    @Autowired
    private OrdererRepository ordererRepository;

    @Autowired
    private ConfigService configService;

    @Autowired
    private HFClient hfClient;

    private List<MOrderer> getMOrderers(String orgId) {
        return ordererRepository.selectList(new EntityWrapper<MOrderer>().eq(Table.Orderer.orgId.getFieldValue(), orgId));
    }

    public LinkedList<Orderer> getOrderers(Org org) throws InvalidArgumentException {
        LinkedList<Orderer> ordererLinkedList = new LinkedList<>();
        List<MOrderer> mOrderers = getMOrderers(org.getOrgId());
        if (mOrderers != null && mOrderers.size() > 0) {
            for (MOrderer mOrderer : mOrderers) {
                ordererLinkedList.add(hfClient.newOrderer(mOrderer.getOrderName(),
                        getOrderLocation(mOrderer),
                        configService.getOrdererProperties(mOrderer.getOrderName(), org.getDomainName())));
            }
            return ordererLinkedList;
        }
        return ordererLinkedList;
    }

    private String getOrderLocation(MOrderer mOrderer) {
        String grpc = "grpc://";
        if (mOrderer.getTlsFlag()) {
            grpc = "grpcs://";
        }
        return grpc + mOrderer.getHostAddress() + ":" + mOrderer.getPort();
    }
}
